/*
 * SearchGoogleFrame.java
 *
 * Created on 28 listopad 2007, 17:27
 */

package pl.edu.pw.mini.gui;

import java.awt.Cursor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import pl.edu.pw.mini.adapter.documents.Document;
import pl.edu.pw.mini.exceptions.ConnectionException;
import pl.edu.pw.mini.state.StateManager;
import pl.edu.pw.mini.adapter.GoogleAdapter;

/**
 * Frame that allows user to search through google documents
 * @author Diana
 */
public class SearchGoogleFrame extends FunctionalFrame {
    
    /** Creates new form SearchGoogleFrame */
    public SearchGoogleFrame() {
        initComponents();
        workbookIndex=GuiHelper.fillTree(treeList,new HashMap<String,Object>());
        GuiHelper.prepareMainDocumentFrame(jTable1,treeList);
        setNewGoogleModel(new ArrayList<Document>());
        
        
    }
    
    
    protected Map<MutableTreeNode, Object> workbookIndex;
    protected GoogleDocumentsTableModel currentGoogleTableModel;
    
    private void setNewGoogleModel(List<Document> data){
        List l=jTable1.getRowSorter().getSortKeys();
        currentGoogleTableModel=new GoogleDocumentsTableModel(data);
        jTable1.setModel(currentGoogleTableModel);
        jTable1.getRowSorter().setSortKeys(l);
        invalidate();        
    }
    
    /**
     * index of current workbook
     */
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        txtPhraseToCheck = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cbxWhereToCheck = new javax.swing.JComboBox();
        btnSearch = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        treeList = new javax.swing.JTree();
        btnClose = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabelStatus = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Szukaj");
        jLabel1.setText("Expresion");

        jLabel2.setText("Search in");

        cbxWhereToCheck.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Content", "Name" }));

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        treeList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                treeListMouseClicked(evt);
            }
        });

        jScrollPane1.setViewportView(treeList);

        btnClose.setText("Close");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabelStatus.setText("Status: Idle");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabelStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(612, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabelStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnClose)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtPhraseToCheck, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
                                .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cbxWhereToCheck, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(btnSearch))))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 657, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPhraseToCheck, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbxWhereToCheck, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSearch))
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnClose)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void treeListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeListMouseClicked
        int[] selRows=treeList.getSelectionRows();
        if (selRows==null || selRows.length!=1){
            return;
        }
        MutableTreeNode selectedNode = (MutableTreeNode)treeList.getSelectionPath().getLastPathComponent();
        Object obj = workbookIndex.get(selectedNode);
        if (obj instanceof List){
            setNewGoogleModel((List<Document>)obj);
        }
    }//GEN-LAST:event_treeListMouseClicked
    
    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCloseActionPerformed
    
    
    private boolean checkCredWithWarning(){
        return GuiHelper.checkGoogleCredWithWarning();
    }
    
    private String getServiceName(){
        return "Google";
    }
    
    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        
        
        if (!checkCredWithWarning() || isWorkerThreadBusy()){
            return;
        }
        String searchStr=txtPhraseToCheck.getText();
        if (searchStr== null){
            return;
        }
        searchStr=searchStr.trim();
        if ("".equals(searchStr)){
            return;
        }
        final String searchStrFinal=searchStr;
        Runnable run=new Runnable(){
            public void run() {
                try {
                    renderBusy("Status: Searching...");
                    String where= (String)cbxWhereToCheck.getSelectedItem();
                    Document.SearchIn searchIn;
                    if(where.equals("Name"))
                        searchIn=Document.SearchIn.NAME;
                    else
                        searchIn=Document.SearchIn.CONTENT;
                    
                    final List<Document> lWb=GoogleAdapter.getAdapter().listDocumentsWithQuery(StateManager.getGoogle(),searchStrFinal,searchIn);
                    SwingUtilities.invokeLater(new Runnable(){
                        public void run() {
                            workbookIndex=GuiHelper.fillTree(treeList,GoogleInterfaceLogic.getInstance().getMapping(lWb));
                            setNewGoogleModel(lWb);
                            treeList.setSelectionRow(0);
                            renderIdle();
                        }
                    });
                } catch (ConnectionException ex) {
                    GuiHelper.exceptionHandler(ex,getServiceName());
                } catch (Exception ex) {
                    GuiHelper.exceptionHandler(ex,getServiceName());
                    
                } finally{
                    renderIdle();
                    markWorkerThreadFinished();
                }
            }
        };
        runSynchIfPossible(run);
    }//GEN-LAST:event_btnSearchActionPerformed
    
    /**
     *
     * @return
     */
    protected JLabel getStatus(){
        return jLabelStatus;
    }
    
    
    
    /**
     * main
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SearchGoogleFrame().setVisible(true);
            }
        });
    }
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnSearch;
    private javax.swing.JComboBox cbxWhereToCheck;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelStatus;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTree treeList;
    private javax.swing.JTextField txtPhraseToCheck;
    // End of variables declaration//GEN-END:variables
    
}
